<?php

/**
 * report actions.
 *
 * @package    DUYTAN
 * @subpackage report
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class reportActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
	$this->search_form = new ReportSearchForm();
	if ($request->hasParameter('report_filter')) {
		$form_data = $request->getParameter('report_filter');
		$this->search_form->bind($form_data);
		$this->search_type = $form_data['search_type'];
		if ($form_data['search_type'] == 1) {
			$q = $this->getDailyQuery($form_data);
			$this->pager = new sfDoctrinePager('DtReportPerDay', 20);
		} elseif ($form_data['search_type'] == 2)
			$q = $this->getWeeklyQuery($form_data);
		else
			$q = $this->getMonthlyQuery($form_data);
	} else {
		if ($request->getParameter('format') == 'Xuất Excel')
			$this->pager = new sfDoctrinePager('DtReportPerDay', 0);
		else
			$this->pager = new sfDoctrinePager('DtReportPerDay', 20);
		$q = Doctrine_Query::create()
			->from('DtReportPerDay d');
		$this->search_type = 1;
	}
	
	$this->sort_by = $request->getParameter('sort_by', 'created_at');
	if ($request->getParameter('sort_order', 1))
        $this->sort_order = 'desc';
    else
        $this->sort_order = 'asc';
	if (Doctrine_Core::getTable('DtReportPerDay')->hasField($this->sort_by))
        $q->orderBy('d.'.$this->sort_by.' '.strtoupper($this->sort_order));
	$this->pager->setQuery($q);
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();
	if ($request->isXmlHttpRequest()) {
        return 'Ajax';
    } else if ($request->getParameter('format') == 'Xuất Excel') {
            $this->setlayout(false);
            $this->getResponse()->setHttpHeader('Content-Type', 'text/csv');
            $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename=bao_cao_ngay' . date("Y-m-d_Hi") . '.csv');
            return 'CSV'; 
	}
	return SfView::SUCCESS;
  }


  private function getDailyQuery($form)
  {
	$q = Doctrine_Query::create()
		->from('DtReportPerDay d');
	if (!empty($form['start_date'])) {
		$date = date('Y-m-d', strtotime($form['start_date']));
		$q->addWhere('DATEDIFF(d.date, "'.$date.'") >= 0');
	}
	if (!empty($form['end_date'])) {
		$date = date('Y-m-d', strtotime($form['end_date']));
		$q->addWhere('d.date >= ?', $date);
	}
	return $q;
  }


  private function getWeeklyQuery($form)
  {

  }


  private function getMonthlyQuery($form)
  {
	
  }
}
